<template>
  <div class="app-container">
  	<header class="app-header">
    	<span class="title">{{$route.meta.title}}</span>
      <el-button type="primary" icon="el-icon-edit" @click.native="addUser()">添加用户</el-button>
    </header>
    <el-form :inline="true" :model="listQuery" class="query-form">
      <el-form-item class="query-form-item">
        <el-autocomplete
          v-model="listQuery.username"
          :fetch-suggestions="querySearch"
          placeholder="请输入用户名"
          :trigger-on-focus="false"
          :clearable = "true"
          @select="handleSelect"
        >
        <template slot-scope="{ item }">
          <div class="name">{{ item.username }}</div>
        </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item class="query-form-item">
        <el-select v-model="listQuery.status" placeholder="请选择状态">
          <el-option label="全部" value="" />
          <el-option label="禁用" value="0" />
          <el-option label="正常" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button-group>
          <el-button type="primary" icon="el-icon-search" @click.native="getList">查询</el-button>
        </el-button-group>
      </el-form-item>
    </el-form>
		<el-table v-loading="loading" border :data="tableList"  @selection-change="handleSelectionChange">
			<el-table-column align="center" width="50" type="selection" />
			<el-table-column align="center"  label="用户ID" prop="id" show-overflow-tooltip />
			<el-table-column align="center"  label="用户名称" prop="username" show-overflow-tooltip />
			<el-table-column align="center"  label="手机号码" prop="phoneNo" show-overflow-tooltip />
      <el-table-column align="center" label="状态" prop="status"  width="80" >
				<template slot-scope="scope">
					<el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ccc" @change="changeStatus(scope.row)"></el-switch>
				</template>
      </el-table-column>
			<el-table-column align="center" label="注册时间" prop="created"  show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.created | parseTime('{y}-{m}-{d} {h}:{i}') }}
        </template>
      </el-table-column>
      <el-table-column align="center"  label="操作">
      	<el-button-group slot-scope="scope">
   				<el-button type="primary" size="mini" @click.native.prevent="editItem(scope.$index,scope.row)">编辑</el-button>
          <el-button type="danger" size="mini"  @click.native.prevent="detItme(scope.$index, scope.row)">删除</el-button>
        </el-button-group>
      </el-table-column>
		</el-table>
		<pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList"/>


    <el-dialog :title="formName" ref="dataForm" :visible.sync="formVisible" :before-close="hideForm"  :close-on-click-modal="false" width="50%" top="5vh">
      <el-form ref="dataForm" :key="1" :model="formData" :rules="addRules">
				<el-form-item label="头像" prop="headerImg" label-width="80px" >
          <SingleUpload ext='jpg/png/gif/jpeg' :imageUrl="imageUrl" @on-select="onSelect"></SingleUpload>
        </el-form-item>
				<el-form-item label="用户名" prop="username" label-width="80px" >
          <el-input v-model="formData.username" placeholder="请输入用户名" auto-complete="off" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNo" label-width="80px" >
          <el-input v-model="formData.phoneNo" placeholder="请输入手机号码" :maxlength="11" auto-complete="off" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password" label-width="80px">
          <el-input v-model="formData.password" placeholder="请输入登录密码，小程序端可免密登录" type="password" auto-complete="off" />
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword" label-width="80px">
          <el-input v-model="formData.checkPassword" placeholder="请确认登录密码，小程序端可免密登录" type="password" auto-complete="off" />
        </el-form-item>
				<div class="dialog-footer" style="text-align:right">
					<el-button @click.native="hideForm">取消</el-button>
					<el-button type="primary" :loading="formLoading" @click.native="formSubmit()">提交</el-button>
				</div>
      </el-form>
		</el-dialog>
  </div>
</template>

<script>
import config from '@/api/bgapi'
import request from '@/utils/request'
import { parseTime } from '@/utils'
import SingleUpload from "@/components/Upload/SingleUpload";
import Pagination from '@/components/Pagination'
import { validUsername,validUsernameOrEmpty } from '@/utils/validate'
export default {
	components: { SingleUpload ,Pagination },
	data() {
		let validateNumLetter = (rule, value, callback) => {
				if (!validUsername(value)) {
						callback(new Error("请输入6-18位数字及小写字母"));
				} else {
						callback();
				}
		};
		let validatePass2 = (rule, value, callback) => {
				if (value !== this.formData.password) {
						callback(new Error("两次输入密码不一致!"));
				} else {
						callback();
				}
		};
		return {
      listQuery: {
				username: '',
        status: '',
        page: this.$route.query.page?Number(this.$route.query.page):1,
        pageSize: 20
      },
			formData:{phoneNo:'',username:'',password:'',checkPassword:'',headerImg:'',sex:1,status:1},
			formName:'添加用户',
			formVisible:false,
			formLoading:false,
			addRules: {
				headerImg: [{ required: true, message: "请上传头像!", trigger: "blur"}],
				username: [{ required: true, message: "请输入用户名!", trigger: "blur"}],
				phoneNo: [{ required: true, message: "请输入手机号码!", trigger: "blur"}],
				password: [
					{ required: true, message: "请输入密码", trigger: "blur" },
					{ validator: validateNumLetter, trigger: "blur" }
				],
				checkPassword: [
					{required: true,message: "请再次输入密码",trigger: "blur"},
					{validator: validatePass2, trigger: "blur"}
				]
			},
			imageUrl:'',
			loading:true,
			tableList:[],
			total:0,
		}
	},
  mounted() {
    this.getList();
  },
  methods: {
		addUser(){
			this.formVisible = true;
			this.imageUrl = '';
			this.formData = {phoneNo:'',username:'',password:'',checkPassword:'',headerImg:'',sex:1,status:1};
			this.formName = "添加用户";
		},
    onSelect(data){
			this.formData.password = this.formData.password == '000000' ? '' : this.formData.password;
			this.formData.headerImg = data.resUrl;
			this.imageUrl = data.imgUrl;
    },
		formSubmit(){
			this.$refs["dataForm"].validate(async valid => {
				if(valid){
					if(this.formData.id){
						this.formLoading = true;
						var res = await request.put(config.users+'/'+this.formData.id,this.formData);
						this.formLoading = false;
						if(res.code == '20000'){
							this.imageUrl = '';
							this.formVisible = false
							this.$message.success('编辑用户成功！');
							this.getList();
							this.resetForm();
						}else{
							this.$message.error('保存失败，请联系管理员！');
						}
					}else{
						this.formLoading = true;
						var res = await request.post(config.users,this.formData);
						this.formLoading = false;
						if(res.code == '20000'){
							this.imageUrl = '';
							this.formVisible = false
							this.$message.success('添加用户成功！');
							this.getList();
							this.resetForm();
						}else{
							this.$message.error('保存失败，请联系管理员！');
						}
					}
				}
			})
		},
		async getList(){
			this.loading = true;
			var res = await request.get(config.users,{ params:this.listQuery } );
			this.loading = false;
			this.tableList = res.data || [];
			this.total = res.totalNum || 0;
		},
    async querySearch(queryString, cb) {
      var res = await request.get(config.users,{params:this.listQuery});
      var restaurants = res.data;
      cb(restaurants);
    },
    handleSelect(item) {
      this.listQuery.username = item.username;
      this.getList();
    },
		detItme(index,row){
        this.$confirm("确认删除该记录吗?", "提示", {
            type: "warning",
        }).then(async () => {
            //var res = await request.post(config.delAdminUrl,{'id':row.id});
            var res = await request.delete(config.users+'/'+row.id);
						if(res.code == '20000'){
              this.$message.success("删除成功");
              this.getList();
            }else{
              this.$message.error(response.message);
            }
        })
        .catch(() => {
            this.$message.info("取消删除");
        });
		},
		editItem(index,row){
			this.formVisible = true
			this.formName = "编辑用户";
			this.imageUrl = process.env.VUE_APP_BASE_API+row.headerImg;
			var obj = {...row};
			obj.password = '000000';
			obj.checkPassword = '000000';
			this.formData = obj;
		},
		async changeStatus(row){
			var res = await request.put(config.users+'/'+row.id,{status:row.status});
			if(res.code != '20000'){
			 this.$message.info("状态更改失败");
			}
		},
    hideForm() {
      // 更改值
      this.formVisible = !this.formVisible;
      this.resetForm();
      return true;
    },
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs["dataForm"].resetFields();
      }
    },
		handleSelectionChange(){

		},


	}
}
</script>
